package com.ambitor.ipro.actions;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import org.apache.struts2.json.annotations.JSON;

import com.ambitor.grass.util.data.DatasetList;
import com.ambitor.grass.util.data.IDataset;
import com.ambitor.ipro.service.TopService;
import com.ambitor.ipro.util.Constants;
import com.ambitor.ipro.util.IDataUtils;
import com.ambitor.ipro.util.StringUtil;
import com.ambitor.ipro.view.Pager;

public class ItemAction extends JsonBaseAction {

	private transient String searchKey;

	private transient boolean refresh = false;

	private transient String cid;

	private transient String approveStatus = "onSale";

	private transient static final long serialVersionUID = -4007353262928075395L;

	public void setSearchKey(String searchKey)
			throws UnsupportedEncodingException {
		this.searchKey = URLDecoder.decode(searchKey,
				Constants.APPLICATION_ENCODING);
	}

	@JSON(serialize = false)
	public String getSearchKey() {
		return searchKey;
	}

	@JSON(serialize = false)
	public String getCid() {
		return cid;
	}

	public void setCid(String cid) {
		this.cid = cid;
	}

	public void setRefresh(boolean refresh) {
		this.refresh = refresh;
	}

	public String getApproveStatus() {
		return approveStatus;
	}

	public void setApproveStatus(String approveStatus) {
		this.approveStatus = approveStatus;
	}

	@JSON(serialize = false)
	public boolean isRefresh() {
		return refresh;
	}

	@Override
	public Pager getPager() {
		return pager;
	}

	@Override
	@SuppressWarnings("unchecked")
	public IDataset getDataset() {
		return dataset;
	}

	@SuppressWarnings("unchecked")
	public String queryItems() throws Exception {
		logger.info("queryItems()方法，开始执行查询");
		if (pager.getCurPageNo() != 1)
			refresh = false; // 同步数据的请求curpageno一定是1，否则不同步，为解决jqgrid的问题而加

		IDataset items = null;
		if ("inventory".equals(this.getApproveStatus())) {
			items = queryInventoryItems(refresh);
		} else {
			items = queryOnSaleItems(refresh);
		}

		items = filterBySearchKey(items);
		items = filterBySellerCat(items);
		pager.setTotalCount(items.size());
		dataset.addAll(items.subList(pager.getFirst(), pager.getEnd()));

		logger.info("共" + pager.getTotalCount() + "条记录");
		logger.info("共" + pager.getTotalPages() + "页");
		logger.info("当前请求的是第" + pager.getCurPageNo() + "页");
		logger.info("从过滤后的结果集中取出从" + (pager.getFirst() + 1) + "到"
				+ pager.getEnd() + "共" + dataset.count() + "条记录.");
		sort();
		logger.info("返回排序后的最终结果.");
		return SUCCESS;
	}

	@SuppressWarnings("unused")
	private IDataset queryAllItems(boolean refresh) throws Exception {
		logger.info("queryAllItems() starting...");
		Object object = pd
				.getSessionAttribute(Constants.SESSEION_INVENTORY_ITEMS);
		IDataset allItems = new DatasetList();
		if (object == null || refresh == true) {
			TopService topService = new TopService(Constants.EVN_SWITCH,
					Constants.APP_KEY_IMPROMOTION,
					Constants.APP_SECRET_IMPROMOTION);
			String sessionId = pd.getTopSessionId();
			String visitorNick = pd.getTopNick();
			allItems = IDataUtils.itemsListToIDataset(topService.getAllItems(
					sessionId, visitorNick));

			pd
					.setSessionAttribute(Constants.SESSEION_INVENTORY_ITEMS,
							allItems);
			logger.info("queryAllItems取出" + allItems.size() + "条数据放到了session中");
		} else {
			allItems = (IDataset) object;
			logger.info("从session中取出" + allItems.count() + "条记录.");
		}
		return allItems;
	}

	private IDataset queryOnSaleItems(boolean refresh) throws Exception {
		logger.info("queryOnsaleItems() starting...");
		Object object = pd.getSessionAttribute(Constants.SESSEION_ONSALE_ITEMS);
		IDataset onSaleItems = new DatasetList();
		if (object == null || refresh == true) {
			TopService topService = new TopService(Constants.EVN_SWITCH,
					Constants.APP_KEY_IMPROMOTION,
					Constants.APP_SECRET_IMPROMOTION);
			String sessionId = pd.getTopSessionId();
			String visitorNick = pd.getTopNick();
			onSaleItems = IDataUtils.itemsListToIDataset(topService
					.getOnSaleItems(sessionId, visitorNick));

			pd
					.setSessionAttribute(Constants.SESSEION_ONSALE_ITEMS,
							onSaleItems);
			logger.info("queryOnSaleItems取出" + onSaleItems.size()
					+ "条数据放到了session中");
		} else {
			onSaleItems = (IDataset) object;
			logger.info("从session中取出" + onSaleItems.count() + "条记录.");
		}
		return onSaleItems;
	}

	private IDataset queryInventoryItems(boolean refresh) throws Exception {
		logger.info("queryInventoryItems() starting...");
		Object object = pd
				.getSessionAttribute(Constants.SESSEION_INVENTORY_ITEMS);
		IDataset inventoryItems = new DatasetList();
		if (object == null || refresh == true) {
			TopService topService = new TopService(Constants.EVN_SWITCH,
					Constants.APP_KEY_IMPROMOTION,
					Constants.APP_SECRET_IMPROMOTION);
			String sessionId = pd.getTopSessionId();
			String nick = pd.getTopNick();
			inventoryItems = IDataUtils.itemsListToIDataset(topService
					.getInventoryItems(sessionId, nick));

			pd.setSessionAttribute(Constants.SESSEION_INVENTORY_ITEMS,
					inventoryItems);
			logger.info("queryInventoryItems取出" + inventoryItems.size()
					+ "条数据放到了session中");
		} else {
			inventoryItems = (IDataset) object;
			logger.info("从session中取出" + inventoryItems.count() + "条记录.");
		}
		return inventoryItems;
	}

	private void sort() {
		if (dataset == null || dataset.size() == 1) {
			logger.info("结果集为空或只有一条，无需排序");
			return;
		}
		int order = IDataset.ORDER_ASCEND;
		int order_type = IDataset.TYPE_STRING;
		if (pager.getOrder() == null || pager.getOrderBy() == null) {
			return;
		}
		if (Constants.PAGER_DESC.equals(pager.getOrder())) {
			order = IDataset.ORDER_DESCEND;
		}
		if (pager.getOrderBy().equalsIgnoreCase("price")) {
			order_type = IDataset.TYPE_DOUBLE;
		}
		dataset.sort(pager.getOrderBy(), order_type, order);
		logger.info("对" + pager.getOrderBy() + "进行" + pager.getOrder() + "排序");
	}

	private IDataset filterBySearchKey(IDataset allItemsOnSale)
			throws Exception {
		logger.info("开始根据searchKey过滤查询出的结果集");
		if (searchKey == null) {
			logger.info("searchKey==null，停止过滤");
			return allItemsOnSale;
		}
		searchKey = searchKey.trim();
		if (searchKey.equals("")) {
			logger.info("searchKey为空，停止过滤");
			return allItemsOnSale;
		}
		String filterStr = StringUtil.buildFilterStr(searchKey,
				new String[] { "title" }, false);
		logger.info("拼出的filter串是" + filterStr);
		IDataset itemOnSaleFiltered = allItemsOnSale.filter(filterStr);

		logger.info("根据关键字共过滤到符合条件的结果" + itemOnSaleFiltered.count() + "条");
		return itemOnSaleFiltered;
	}

	private IDataset filterBySellerCat(IDataset items) throws Exception {
		logger.info("开始根据SellerCat过滤查询出的结果集");
		if (cid == null) {
			logger.info("cid==null，停止过滤");
			return items;
		}
		cid = cid.trim();
		if (cid.equals("") || cid.equals("all_cats")) {
			logger.info("cid为空或者cid='all_cats'，停止过滤");
			return items;
		}
		String filterStr = "seller_cids~" + cid;
		logger.info("filterStr==" + filterStr);
		IDataset itemsFiltered = items.filter(filterStr);
		logger.info("根据cid共过滤到符合条件的结果" + itemsFiltered.count() + "条");
		return itemsFiltered;
	}

}
